package com.example.sharedpreferences;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.sharedpreferences.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        checkRemember();
    }

    private void initView() {
        binding.btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String username = binding.etUsername.getText().toString();
                String password = binding.etPassword.getText().toString();

                if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
                    if (binding.cbRemember.isChecked()) {
                        remember(username, password);
                    } else {
                        clear();
                    }
                    Toast.makeText(MainActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void remember(String username, String password) {
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("username", username);
        edit.putString("password", password);
        edit.apply();

//        sp.edit().putString("username", username)
//                .putString("password", password)
//                .apply();
    }

    private void checkRemember() {
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        binding.etUsername.setText(sp.getString("username", ""));
        binding.etPassword.setText(sp.getString("password", ""));
    }

    private void clear() {
        SharedPreferences sp = getSharedPreferences("user", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        // edit.remove("username");
        edit.clear();
        edit.apply();

        // sp.edit().clear().apply();
    }


}